﻿using System;
using System.Linq;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Reflection;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using Opds_Viewer.Model;
using Opds_Viewer.Properties;

namespace Opds_Viewer.ViewModel
{
    public class InitViewModel : ViewModelBase
    {
        #region Private fields

        private string _description;

        // Commanding
        private readonly RelayCommand _startCommand;
        
        #endregion

        #region constructor
        
        /// <summary>
        /// Initializes a new instance of the <see cref="InitViewModel"/> class.
        /// </summary>
        public InitViewModel()
        {
            _startCommand = new RelayCommand(Start);
        }

        #endregion

        #region commanding

        /// <summary>
        /// Start the initialization
        /// </summary>
        public ICommand StartCommand
        {
            get { return _startCommand; }
        }

        #endregion

        #region public properties

        /// <summary>
        /// Gets or sets the description.
        /// </summary>
        /// <value>The description.</value>
        public string Description
        {
            get { return _description; }
            set
            {
                _description = value;
                RaisePropertyChanged("Description");
            }
        }

        /// <summary>
        /// Get the version of the application.
        /// </summary>
        /// <value>The version.</value>
        public string Version
        {
            get { return Assembly.GetExecutingAssembly().GetName().Version.ToString(); }
        }

        #endregion

        #region private functions

        /// <summary>
        /// Starts the treatment in a separate thread.
        /// </summary>
        private void Start()
        {
            var worker = new BackgroundWorker();
            worker.DoWork += WorkerDoWork;
            worker.RunWorkerCompleted += WorkerRunWorkerCompleted;
            worker.RunWorkerAsync();
        }

        /// <summary>
        /// Close the view and open the main one when the worker is completed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.ComponentModel.RunWorkerCompletedEventArgs"/> instance containing the event data.</param>
        private void WorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            var main = new MainWindow();
            main.Show();
            Messenger.Default.Send(new NotificationMessage("CloseTheView"));
        }

        /// <summary>
        /// The long treatment in the backgroundworker.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.ComponentModel.DoWorkEventArgs"/> instance containing the event data.</param>
        private void WorkerDoWork(object sender, DoWorkEventArgs e)
        {
            InitCatalogs();
        }

        /// <summary>
        /// Inits the catalogs.
        /// </summary>
        private void InitCatalogs()
        {
            this.Description = "Initialisation des catalogues...";
            // Load all the catalogs to check with the last date of the version we have
            var catalogs = MyCatalogs.Instance;

            var count = catalogs.Where(c => c.ToUpdate).Count();
            this.Description = count + " catalogues à mettre à jour...";

            var i = 0;
            foreach (var catalog in catalogs.Where(c => c.ToUpdate))
            {
                try
                {
                    this.Description = "Téléchargement " + i + "/" + count + "...";

                    // Check id the directory exists
                    var dir = Settings.Default.DirCatalogs + "/" + catalog.Name;
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }

                    // If the version on the web is newer, we download it
                    using(var wc = new WebClient())
                    {
                        // Download the db
                        var tmpAddr = dir + "/" + Settings.Default.NameDb;
                        wc.DownloadFile(catalog.UrlDb, tmpAddr);

                        // Finally, get the last update date
                        // and save the config file of the catalogs
                        var info = new FileInfo(tmpAddr);
                        if (info.Exists)
                        {
                            catalog.DateMaj = info.CreationTime;
                            catalog.FileDb = tmpAddr;
                            catalog.Save();
                        }
                    }

                    i++;
                }
                catch (Exception ignore)
                {
                    // If the download fails, we just ignore it
                    catalog.DateMaj = DateTime.MinValue;
                    catalog.FileDb = string.Empty;
                    catalog.UrlDb = string.Empty;
                    catalog.Status = false;
                    catalog.Save();
                }
            }
        }

        #endregion

    }
}
